<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<input type="text" placeholder="条码/名称/拼音码" class="search-input" @click="select" />
			<view @click="startScan" style="display: flex; align-items: center; justify-content: center;">
				<view @click="startScan"
					style="width: 75px;height: 75px;display: flex; align-items: center; justify-content: center;background-color: #007aff;">
					<image style="width: 50px;height: 50px;" src="/static/icon/扫码.png"></image>
				</view>
			</view>
		</view>

		<!-- 商品分类和商品展示区 -->
		<view class="content">
			<!-- 商品分类区 -->
			<scroll-view class="category-list" scroll-y="true">
				<view class="category-item" @click="selectProducts" :class="{'active': selectIndex===-1}" >全部</view>
				<view class="category-item" v-for="(item, index) in categories" :key="index.typeId"
					:class="{'active': selectIndex===index}" @click="chooseClassify(item.typeId,index)">
					{{ item.typeName }}
				</view>
			</scroll-view>

			<!-- 商品展示区 -->
			<scroll-view class="product-list" scroll-y="true">
				<view class=product-list-span>
					<span @click="productTimeDescending">时间<svg t="1742367790939" class="icon" viewBox="0 0 1024 1024"
							version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2629" width="20" height="20">
							<path
								d="M512 231.232l170.688 170.688H341.312L512 231.232zM512 793.216L341.312 622.528h341.376L512 793.216z"
								fill="#C2C9CF" p-id="2630"></path>
						</svg></span>
					<span @click="productRetailPriceDescending"> 价格<svg t="1742367790939" class="icon"
							viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2629"
							width="20" height="20">
							<path
								d="M512 231.232l170.688 170.688H341.312L512 231.232zM512 793.216L341.312 622.528h341.376L512 793.216z"
								fill="#C2C9CF" p-id="2630"></path>
						</svg></span>
				</view>
				<view v-for="(item, index) in products" :key="index.productId" class="product-item">
					<view class="product-image">
						<image :src="item.productImageUrl" class="placeholder" />
					</view>
					<view class="product-info" @click="goDetailsPage(item.productId)">
						<ul class="product-list">
							<li class="product-name">{{ item.productName }}</li>
							<li class="product-code">{{ item.stockquantity }}</li>
							<li class="product-price">¥{{ item.retailPrice }}/{{item.unitName}}</li>
						</ul>
					</view>
					<view class="add-button" @click="addToCart(item)">+</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>


<script>
	import {
		ref
	} from 'vue';
	import store from '../../store';
	export default {
		data() {
			return {
				selectIndex:-1,
				categories: [], //分类
				products: [], //商品
				sortByTime: 'asc', // 默认按时间升序
				sortByPrice: 'asc', // 默认按价格升序
			};
		},
		methods: {
			// 添加到收银台
			addToCart(product) {
			  const newItem = {
			      productId: product.productId,
			      productName: product.productName,
			      retailPrice: product.retailPrice,
			      productImageUrl: product.productImageUrl,
			      qutity: 1,
			      barcode: product.barcode
			    };
				// console.log("newItem",newItem)
			    // 分发 action 到 Vuex store 来更新 products
			    store.dispatch('addProduct', newItem);
			},
			selectCategory(index) {
				this.categories.forEach((category, idx) => {
					category.active = idx === index;
				});
			},
			//根据商品id跳转商品详情
			goDetailsPage(productId) {
				const app = getApp();
				const url = app.globalData.url;
				uni.request({
					url: url + "PRODUCT-SERVICE/product/selectByIdWx?productId=" + productId,
					method: "GET",
					success: (res) => {
						if (res.statusCode === 200) {
							this.productDetails = res.data; // 假设你有一个变量来存储商品详情
							console.log(this.productDetails);
							// 跳转到详情页，并传递商品详情
							uni.navigateTo	({
								url: '/pages/ProductDetails/ProductDetails?productId=' + productId
							});
						} else {
							uni.showToast({
								title: "加载失败",
								icon: "none"
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: "网络请求错误",
							icon: "none"
						});
					}
				});
			},
			//搜索跳转
			select() {
				uni.navigateTo({
					url: '/pages/searProduct/searProduct'
				})
			},
			// 按时间排序
			productTimeDescending() {
				if (this.sortByTime === 'asc') {
					this.products.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
					this.sortByTime = 'desc';
				} else {
					this.products.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
					this.sortByTime = 'asc';
				}
			},
			// 按价格排序
			productRetailPriceDescending() {
				if (this.sortByPrice === 'asc') {
					this.products.sort((a, b) => b.retailPrice - a.retailPrice);
					this.sortByPrice = 'desc';
				} else {
					this.products.sort((a, b) => a.retailPrice - b.retailPrice);
					this.sortByPrice = 'asc';
				}
			},

			//查询全部商品
			selectProducts() {
				this.selectIndex=-1
				const app = getApp();
				const url = app.globalData.url;
				uni.request({
					url: url + 'PRODUCT-SERVICE/product/selAll',
					method: "GET",
					success: (res) => {
						if (res.statusCode === 200) {
							this.products = res.data;
							console.log(this.products = res.data)
						} else {

							uni.showToast({
								title: "加载失败",
								icon: "none"
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: "网络请求错误",
							icon: "none"
						});
					}
				});
			},


			//查询全部分类
			selectCategories() {
				const app = getApp();
				const url = app.globalData.url;
				uni.request({
					url: url + 'PRODUCT-SERVICE/productType/selectProductTypeParentId',
					method: "GET",
					success: (res) => {
						if (res.statusCode === 200) {
							this.categories = res.data;
							console.log(this.categories = res.data)
						} else {

							uni.showToast({
								title: "加载失败",
								icon: "none"
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: "网络请求错误",
							icon: "none"
						});
					}
				});
			},

			//根据商品分类查询商品
			chooseClassify(typeId,index) {
				this.selectIndex=index;
				const app = getApp();
				const url = app.globalData.url;
				uni.request({
					url: url + 'PRODUCT-SERVICE/product/getProductsBySubclasses?typeId=' + typeId,
					method: "GET",
					success: (res) => {
						if (res.statusCode === 200) {
							this.products = res.data;
							console.log(this.products = res.data)
						} else {

							uni.showToast({
								title: "加载失败",
								icon: "none"
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: "网络请求错误",
							icon: "none"
						});
					}
				});
			},
			// 扫码查询商品
			    async startScan() {
			      try {
			        const res = await new Promise((resolve, reject) => {
			          uni.scanCode({
			            scanType: ['barCode', 'qrCode'],
			            success: (res) => {
			              console.log('Scan success:', res);
			              resolve(res);
			            },
			            fail: (err) => {
			              // 提供更详细的错误信息
			              console.error('Scan failed with error:', err);
			              if (err.errMsg) {
			                console.error('Error message:', err.errMsg);
			              }
			              reject(err);
			            }
			          });
			        });

			        console.log('Scan result:', res.result);
			        this.navigateToSearchPage(res.result);
			      } catch (err) {
			        console.error('Detailed scan error:', err.errMsg || JSON.stringify(err));
			        uni.showToast({
			          title: '扫码失败，请重试',
			          icon: 'none',
			          duration: 2000
			        });
			      }
			    },
			    // 跳转到搜索页面的方法
			    navigateToSearchPage(barcode) {
			      uni.navigateTo({
			        url: `/pages/searProduct/searProduct?barcode=${encodeURIComponent(barcode)}`
			      });
			    }
		},
		mounted() {
			this.selectProducts(); // 确保在页面加载时调用
			this.selectCategories();
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: white;
		border-bottom: 1px solid #e5e5e5;
	}

	.search-input {
		flex: 1;
		padding: 10px;
		border: none;
		border-radius: 5px;
	}

	.scan-button {
		background-color: transparent;
		border: none;
		color: #007aff;
		font-size: 16px;
	}

	.content {
		display: flex;
		flex: 1;
	}

	.category-list {
		display: flex;
		flex-direction: column;
		text-align: center;
		height: 4050px;
		width: 30%;
		background-color: #f1f1f1;
		/* border: 1px solid; */
	}

	.category-item {
		padding: 10px;
		font-size: 16px;
		color: #666;
	}



	.category-item:hover {
		color: #007aff;
		font-weight: bold;
		background-color: white;
		width: 100%;
	}

	.product-list {
		width: 70%;
		background-color: white;
		margin-left: 10px;
	}

	.product-item {
		display: flex;
		align-items: center;
		padding: 10px;
		border-bottom: 1px solid #e5e5e5;
	}

	.product-image {
		width: 80px;
		height: 80px;
		background-color: #eee;
		margin-right: 10px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.placeholder {
		color: #ccc;
		width: 80px;
		height: 80px;
	}

	.product-info {
		flex: 1;
	}

	.product-list {
		list-style-type: none;
		padding: 0;
		margin: 0;
		width: 75%;
		background-color: white;
		margin-left: 10px;
		text-align: left;
	}

	.product-list li {
		margin-bottom: 5px;
		text-align: left;

	}

	.product-name {

		font-size: 16px;
		color: #333;
	}

	.product-code {
		font-size: 14px;
		color: #666;
	}

	.product-price {
		font-size: 16px;
		color: #007aff;
	}

	.add-button {
		width: 25px;
		height: 25px;
		text-align: center;
		background-color: #007aff;
		color: white;
		padding: 0px 0px;
		border-radius: 50px;
		margin-top: 50px;
	}

	.footer {
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 10px 0;
		background-color: #f5f5f5;
		position: fixed;
		bottom: 0;
		width: 100%;
		box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
		z-index: 10;
		/* 确保导航栏在最上层 */
	}

	.nav {
		display: flex;
		justify-content: space-around;
		width: 100%;
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 14px;
	}

	.nav-icon {
		font-size: 24px;
		margin-bottom: 5px;
	}

	.nav-text {
		font-size: 14px;
	}

	.nav-item.active {
		color: #007aff;
	}

	.active{
		    color: #007aff;
		    font-weight: bold;
		    background-color: white;
		    width: 100%;
	}


	.product-list-span {
		display: flex;
		justify-content: space-around;
		color: #b9b9b9;
	}

	.product-list-span :hover {
		color: #007aff;
	}
</style>